import numpy as np
import pandas as pd
from fractions import Fraction
import statsmodels.api as sm

# 设置矩阵元素输出用分数表示
np.set_printoptions(formatter={'all': lambda x: str(Fraction(x).limit_denominator())})
# 这里如果不设置header=None默认就将数据第一行当作数据头
'''
当前年薪y(美元),开始年薪x1(美元),工作时间x2(月),先前工作经验x3(月),受教育年限x4(年)
corr()求解变量相关系数
'''
df = pd.read_csv("F:/成信大/多元统计分析/test2-1.csv")
print(df)
y = df['当前年薪']
x1 = df['开始年薪']
x2 = df['工作时间']
x3 = df['先前工作经验']
x4 = df['受教育年限']
print("当前年薪与开始年薪的相关系数:", y.corr(x1))
# print("当前年薪与工作时间的相关系数:", y.corr(x2))
# print("当前年薪与先前工作经验的相关系数:", y.corr(x3))
# print("当前年薪与受教育年限的相关系数:", y.corr(x4))
y_x2x4 = (x2.corr(x4) - x2.corr(y) * x4.corr(y)) / (((1 - x2.corr(y)**2)**0.5) * ((1 - x4.corr(y)**2)**0.5))
print(y_x2x4)
# y_x2x4 = (x2.corr(y) - x2.corr(x4) * y.corr(x4)) / (((1 - x2.corr(x4)**2)**0.5) * ((1 - y.corr(x4)**2)**0.5))
# print("当前年薪和工作时间和受教育年限的偏相关系数:", y_x2x4)
# 根据SPSS得出各个系数结果为x1=1.665,x2=-24.182,x3=-15.480,x4=903.685,常量为-2243.096
constant = -2243.096
c_x1 = +1.665
c_x2 = -24.182
c_x3 = -15.480
c_x4 = +903.685
print(sm.OLS(y, x1))
print("线性回归方程为：y(当前年薪) = {}*x1(开始年薪){}*x2(工作时间){}*x3(先前工作经验)+{}*x4(受教育年限){}".format(c_x1, c_x2, c_x3, c_x4, constant))
